//
//  MakeMoneyViewController.m
//  RENTVISITOR
//
//  Created by wonder on 2017/9/29.
//  Copyright © 2017年 UNN. All rights reserved.
//

#import "MakeMoneyViewController.h"
#import "RentVieitor.h"
#import <UMSocialCore/UMSocialCore.h>




@interface MakeMoneyViewController ()
@property (nonatomic , strong)UIAlertView *myAlertView;
@property (nonatomic , strong)UIAlertView *myAlertView2;


@end

@implementation MakeMoneyViewController

- (void)viewWillAppear:(BOOL)animated {
    
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:17],
       NSForegroundColorAttributeName:[Utils colorConvertFromString:@"#333333"]}];
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.hidden = NO;

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [self creatView];
    
       
}


- (void)creatView {
    
    
    //number会员编号
    NSDictionary *dataDic = User_listsValue;
    NSString *rUrl = [NSString stringWithFormat:@"%@%@",RURL,dataDic[@"number"]];
    
    // 1. 创建一个二维码滤镜实例(CIFilter)
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 滤镜恢复默认设置
    [filter setDefaults];
    
    // 2. 给滤镜添加数据
    
    NSData *data = [rUrl dataUsingEncoding:NSUTF8StringEncoding];
    // 使用KVC的方式给filter赋值
    [filter setValue:data forKeyPath:@"inputMessage"];
    
    // 3. 生成二维码
    CIImage *image = [filter outputImage];
    
    UIImage *img = [self createNonInterpolatedUIImageFormCIImage:image withSize:160];
    
    
    //开启绘图,获取图形上下文  (上下文的大小,就是二维码的大小)
    UIGraphicsBeginImageContext(img.size);
    
    //把二维码图片画上去. (这里是以,图形上下文,左上角为 (0,0)点)
    [img drawInRect:CGRectMake(0, 0, img.size.width, img.size.height)];
    
    
    //再把小图片画上去
    UIImage *sImage = [UIImage imageNamed:@"icon-l"];
    
    //
    //    UIImageView *sImageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 60, 60)];
    //    [self.view addSubview:sImageView];
    //    sImageView.image = sImage;
    //    // 类似于clip，使用masksToBounds阴影效果无效
    //    sImageView.layer.masksToBounds = YES;
    //    //图层的圆角半径
    //    sImageView.layer.cornerRadius = 50;
    
    
    
    CGFloat sImageW = 50;
    CGFloat sImageH= sImageW;
    CGFloat sImageX = (img.size.width - sImageW) * 0.5;
    CGFloat sImgaeY = (img.size.height - sImageH) * 0.5;
    
    [sImage drawInRect:CGRectMake(sImageX, sImgaeY, sImageW, sImageH)];
    
    //获取当前画得的这张图片
    UIImage *finalyImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭图形上下文
    UIGraphicsEndImageContext();
    

    
    // 4. 显示二维码
    
    UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 170, KWidth-40, 20)];
    myLabel.text = @"我的二维码";
    myLabel.font = [UIFont systemFontOfSize:14];
    myLabel.textAlignment = NSTextAlignmentCenter;
    myLabel.textColor = [Utils colorConvertFromString:@"#333333"];
    [self.view addSubview:myLabel];
    
//    UILabel *qLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 200+180, KWidth-40, 20)];
//    qLabel.text = [NSString stringWithFormat:@"我的链接:%@",rUrl];
//    qLabel.font = [UIFont systemFontOfSize:14];
//    qLabel.textAlignment = NSTextAlignmentCenter;
//    qLabel.textColor = [Utils colorConvertFromString:@"#333333"];
//    [self.view addSubview:qLabel];

    
    UIImageView *logoView = [[UIImageView alloc] initWithFrame:CGRectMake((KWidth-160)/2, 200, 160, 160)];
    logoView.tag = 10001;
    logoView.userInteractionEnabled = YES;
    logoView.image = finalyImage;
    //长按
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPassAction:)];
    [logoView addGestureRecognizer:longPress];
    //判定为长按手势 需要的时间
    longPress.minimumPressDuration = 1;
    //判定时间,允许用户移动的距离
    longPress.allowableMovement = 100;
    [self.view addSubview:logoView];
    
//    UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
//    logo.image = [UIImage imageNamed:@"icon-l"];
//    logo.center = logoView.center;
//    [self.view addSubview:logo];
    
    
    //租客网
    UIImageView *imgView =  [[UIImageView alloc] initWithFrame:CGRectMake((KWidth-90)/2, 60, 90, 30)];
    imgView.image = [UIImage imageNamed:@"租客网"];
    [self.view addSubview:imgView];
    
    UILabel *selectLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, KWidth-40, 30)];
    selectLabel.text = @"轻松分享,酣赚租金";
    selectLabel.font = [UIFont systemFontOfSize:17];
    selectLabel.textAlignment = NSTextAlignmentCenter;
    selectLabel.textColor = [Utils colorConvertFromString:@"#333333"];
    [self.view addSubview:selectLabel];
    
    //分割线
    CALayer *MlineLayer72 = [CALayer layer];
    MlineLayer72.backgroundColor = [[Utils colorConvertFromString:@"#d0d0d0"] CGColor];
    MlineLayer72.frame = CGRectMake(50 ,150, KWidth-100, 1);
    [self.view.layer addSublayer:MlineLayer72];

    
    //朋友圈
    NSArray *imgArray = @[@"share_weiCircle",@"share_weinxin",@"WeiboL",@"share_qzone"];
    NSArray *titleArray = @[@"朋友圈",@"微信",@"微博",@"QQ空间"];
    CGFloat width = 50;
    CGFloat margin = 15;
    CGFloat x = (KWidth-margin*3-50*4)/2;
    for (int i=0; i<imgArray.count; i++) {
        
        UIButton *weicircleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [weicircleButton setImage:[UIImage imageNamed:imgArray[i]] forState:UIControlStateNormal];
        weicircleButton.frame = CGRectMake(x+i*(margin+width)+5, logoView.frame.size.height+logoView.frame.origin.y+50, 40, 40);
        weicircleButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
        weicircleButton.tag = i+100;
//        weicircleButton.backgroundColor = [UIColor redColor];
        [weicircleButton addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:weicircleButton];
        
        UILabel *weicircleLabel = [[UILabel alloc] init];
        weicircleLabel.frame = CGRectMake(x+i*(margin+width), logoView.frame.size.height+logoView.frame.origin.y+50+40, 50, 20);
        weicircleLabel.textColor = [Utils colorConvertFromString:@"#101010"];
        weicircleLabel.text = titleArray[i];
        
//        weicircleLabel.backgroundColor = [UIColor redColor];
        weicircleLabel.textAlignment = NSTextAlignmentCenter;
        weicircleLabel.font = [UIFont systemFontOfSize:14];
        [self.view addSubview:weicircleLabel];
    }

    
//    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeSystem];
//    loginBtn.frame = CGRectMake((KWidth-200)/2, 410, 200, 30);
//    [loginBtn setBackgroundColor:[UIColor colorWithRed:249/255.0 green:105/255.0 blue:39/255.0 alpha:1]];
//    [loginBtn setTitle:@"复制链接" forState:UIControlStateNormal];
//    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    loginBtn.layer.masksToBounds = YES;
//    [loginBtn addTarget:self action:@selector(copeAction) forControlEvents:UIControlEventTouchUpInside];
//    loginBtn.layer.cornerRadius = 2;
//    [self.view addSubview:loginBtn];
    
}


#pragma shar
- (void)shareAction:(UIButton *)button {
    
    
    
//    [APPDELEGATE showPro:@"功能完善中"];
//    return;
    UMSocialPlatformType type;
    
    if (button.tag == 100) {
        
        type = UMSocialPlatformType_WechatTimeLine;
        
    }else if (button.tag == 101) {
        
         type = UMSocialPlatformType_WechatSession;
        
    }else if (button.tag == 102) {
        
        type = UMSocialPlatformType_Sina;
        
    }else {
        
        type = UMSocialPlatformType_Qzone;
    }
    //number会员编号
    NSDictionary *dataDic = User_listsValue;
    NSString *rUrl = [NSString stringWithFormat:@"%@%@",RURL,dataDic[@"number"]];

    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    UIImage *shareImage = [UIImage imageNamed:@"icon-l"];
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"分享" descr:@"租客网注册" thumImage:shareImage];
    //设置网页地址
    shareObject.webpageUrl = rUrl;
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
//    
//    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"分享标题" descr:@"分享的内容" thumImage:[UIImage imageNamed:@"head@2x"]];
//    //设置网页地址
//    shareObject.webpageUrl = @"http://www.talkmoney.cn";
//    
//    
//    //创建分享消息对象
//    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
//    //分享消息对象设置分享内容对象
//    messageObject.shareObject = shareObject;
    
    
    
    /**
     设置分享
     
     @param data 分享返回信息
     @param error 失败信息
     @param UMSocialPlatformType 分享平台
     */
    [[UMSocialManager defaultManager] shareToPlatform:type  messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
            NSInteger code = error.code;
            if (code == 2008) {
                
                [APPDELEGATE showPro:@"应用未安装"];
            }
            
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];

}

//长按手势
- (void)longPassAction:(UILongPressGestureRecognizer *)longPress{
    NSLog(@"11111");
    //长按手势
    if (longPress.state == UIGestureRecognizerStateBegan) {
        self.myAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您要保存当前图片到相册中吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"保存", nil];
        [self.myAlertView show];
        
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        // 保存照片(获取到点击的 image)
        //        NSInteger i = self.scroll.contentOffset.x / self.scroll.bounds.size.width;
        UIImageView *myImageView = (UIImageView *)[self.view viewWithTag:10001];
        UIImageWriteToSavedPhotosAlbum(myImageView.image, self, @selector(image:didFinshSavingWithError:contextInfo:), nil);
    }
    
}
// 保存图片错误提示方法
- (void)image:(UIImage *)image didFinshSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
    NSString *mes = nil;
    if (error != nil) {
        mes = @"保存图片失败";
    } else {
        mes = @"保存图片成功";
    }
    self.myAlertView2 = [[UIAlertView alloc] initWithTitle:@"提示" message:mes delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [self.myAlertView2 show];
    [NSTimer scheduledTimerWithTimeInterval:0.8f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
}

- (void)performDismiss:(NSTimer *)timer
{
    [self.myAlertView2 dismissWithClickedButtonIndex:0 animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}  


- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

- (void)copeAction {
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    NSDictionary *dataDic = User_listsValue;
    NSString *rUrl = [NSString stringWithFormat:@"%@%@",RURL,dataDic[@"number"]];
    pasteboard.string = rUrl;
    [APPDELEGATE showPro:@"复制成功"];

}





@end
